package com.chenwenxuan.sync;

import java.lang.reflect.InvocationTargetException;
import java.util.Hashtable;
import java.util.UUID;

import javax.swing.SwingUtilities;

import org.apache.log4j.xml.DOMConfigurator;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.chenwenxuan.sync.console.TaskInvoker;
import com.chenwenxuan.sync.event.Event;
import com.chenwenxuan.sync.event.EventsManager;
import com.chenwenxuan.sync.event.IEventHandler;
import com.chenwenxuan.sync.event.IEventSource;
import com.chenwenxuan.sync.ui.AppWindow;

public class Application implements IEventSource {

	private FileSystemXmlApplicationContext appContext;
	private String id;
	private EventsManager eventsManager;
	
	public enum EventType {TP_TASK_BEFORE_EXECUTE_EVENT, TP_TASK_AFTER_EXECUTE_EVENT};
	
	private static final Event [] events = new Event[]
			{new Event(EventType.TP_TASK_BEFORE_EXECUTE_EVENT.toString()), new Event(EventType.TP_TASK_AFTER_EXECUTE_EVENT.toString())};
	
	static Application application;
	
	
	public static Application getApplication() {
		return application;
	}
	
	public Object getBean(String name){
		return appContext.getBean(name);
	}
	
	public TaskInvoker createTaskInvoker() {
		return (TaskInvoker) getBean("taskInvoker");
	}
	
	private Application() {
		id = UUID.randomUUID().toString();
		eventsManager = new EventsManager(this, events);
	}
	
	
	public static void main(String[] args) {
		
		DOMConfigurator.configure("./conf/log4j.xml");
		
		application = new Application();
		application.startSpring();
		
	}
	
	private void startSpring() {
		appContext = new FileSystemXmlApplicationContext("./conf/applicationContext.xml");
		appContext.start();
	}
	
	void stopString() {
		appContext.destroy();
	}

	public void addEventHandler(IEventHandler target, EventType eventType) {
		eventsManager.addEventHandler(target, eventType.toString());
		addEventHandler(target, eventType.toString());
	}

	public void removeEventHandler(IEventHandler target, EventType eventType) {
		removeEventHandler(target, eventType.toString());
	}
	
	public void raiseEvent(EventType eventType, Hashtable<String, Object> params) {
		eventsManager.raiseEvent(eventType.toString(), params);
	}

	@Override
	public void addEventHandler(IEventHandler target, String event) {
		eventsManager.addEventHandler(target, event);
	}

	@Override
	public void removeEventHandler(IEventHandler target, String event) {
		eventsManager.addEventHandler(target, event);
	}
	
	
	@Override
	public String getId() {
		return id;
	}
	
	
}
